package com.wut.jmx.controller;

import com.wut.jmx.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
@Api(tags = "文件的上传与下载")
public class CommonController {
    @Value("${ptg.path}")
    private String bashPath;
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        File dir = new File(bashPath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(bashPath + fileName));
        }catch (IOException e){
            e.printStackTrace();
        }
        return R.success(fileName);
    }
    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        log.info("下载文件，文件名：{}", name);
        try(FileInputStream fileInputStream = new FileInputStream(new File(bashPath + name));
            ServletOutputStream outputStream = response.getOutputStream();){
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
        }catch (Exception e){
            log.error("文件下载失败,异常信息:{}",e);
        }
    }
}
